package com.binhthuan.catechist.client.data;

import com.binhthuan.catechist.shared.constant.Parameter;
import com.binhthuan.catechist.shared.constant.Service;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.types.FieldType;

public class ShiftDS extends AbstractDS {

    private static ShiftDS instance;
    private DateTimeFormat timeFormatter = DateTimeFormat.getFormat(PredefinedFormat.HOUR24_MINUTE);

    public ShiftDS() {
        super(Service.SHIFT);

        DataSourceIntegerField id = new DataSourceIntegerField(Parameter.ID);
        id.setHidden(true);
        id.setPrimaryKey(true);

        DataSourceTextField name = new DataSourceTextField(Parameter.NAME);

        DataSourceTextField dayOfWeek = new DataSourceTextField(Parameter.DAY_OF_WEEK);

        DataSourceField startTime = new DataSourceField(Parameter.START_TIME, FieldType.DATETIME);

        DataSourceField endTime = new DataSourceField(Parameter.END_TIME, FieldType.DATETIME);

        setFields(id, name, dayOfWeek, startTime, endTime);
    }

    public static ShiftDS getInstance() {
        if (instance == null) {
            instance = new ShiftDS();
        }
        return instance;
    }

    @Override
    protected void transformResponse(DSResponse response, DSRequest request, Object data) {
        for (Record r : response.getData()) {
            r.setAttribute(Parameter.START_TIME, timeFormatter.format(r.getAttributeAsDate(Parameter.START_TIME), TimeZone.createTimeZone(0)));
            r.setAttribute(Parameter.END_TIME, timeFormatter.format(r.getAttributeAsDate(Parameter.END_TIME), TimeZone.createTimeZone(0)));
        }
        super.transformResponse(response, request, data);
    }
}
